<template>
  <div class="content-view">
    <!-- 工具栏 -->
    <div class="tool-bar">
      <div class="view">
        <el-input placeholder="按名称关键字筛选" v-model="searchKey.words" clearable>
          <template #suffix>
            <i class="iconfont icon-sousuo"></i>
          </template>
        </el-input>
        <!-- 条件搜索 -->
        <condition-query :data="data" @search="searchDone" />
      </div>
      <div class="view end">
        <el-button type="primary" @click="handleBtn(0, {name: ''}, 'add')" v-if="user.power*1 > 80">
          <i class="iconfont icon-xinjian"></i>新建固件
        </el-button>
        <!-- <el-button type="warning" @click="handleBatch" v-if="user.power*1 > 80">
          <i class="iconfont icon-jurassic_batch-work"></i>批量处理
        </el-button> -->
      </div>
    </div>
    <!-- 表格 -->
    <el-table 
      :data="romList.filter(data => !searchKey.words || data.firmware_name.toLowerCase().includes(searchKey.words.toLowerCase()))"
      border stripe
      v-loading="loading" 
      :default-sort="{prop: 'dtCreate', order: 'ascending'}"
      @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="center"/> -->
      <!-- <el-table-column label="固件状态" sortable width="105" :show-overflow-tooltip="true" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status == 0?'success':'danger'">
            {{scope.row.status == 0?'正常':'停用'}}
          </el-tag> 
        </template>
      </el-table-column> -->
      <el-table-column prop="firmware_name" label="固件名称" width="260" sortable  :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="board.model" label="主板型号" sortable width="150" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="board.factory.factory" label="主板厂商" sortable width="150" :show-overflow-tooltip="true"> </el-table-column>
      <!-- <el-table-column label="固件最新版本" sortable width="150" align="center">
        <template #default="scope">
          <el-popover placement="top-start" :width="300" trigger="hover">
            <template #reference>
              <el-text type="primary" style="cursor: pointer;">{{scope.row.edition_infos[scope.row.edition_infos.length - 1].version}}</el-text>
            </template>
            <template #default>
              <div v-for="item in scope.row.edition_infos" :key="item.ver_order" style="padding: 3px;">
                <el-tag>{{item.version}}</el-tag>
                {{item.edition}}
                <el-tooltip effect="dark" :content="item.url" placement="top">
                  <el-button @click="romDownLoad(item.url)" size="small" type="success">下载</el-button>
                </el-tooltip>
              </div>
            </template>
          </el-popover>
        </template>
      </el-table-column> -->
      <el-table-column prop="lastVerion" label="固件最新版本" sortable width="150" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="lastEdtion" label="版本名称" sortable width="150" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="firmware_file_name" label="固件文件名" sortable :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column label="操作" fixed="right" width="100" align="center">
        <template #default="scope">
          <el-button type="success" size="small" @click="handleBtn(scope.$index, scope.row, 'edit')">编辑</el-button>
          <!-- <el-button type="warning" size="small" @click="handleBtn(scope.$index, scope.row, 'del')">状态</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <page-div ref="PAGING_COM" @change="pageChange" />
    <!-- dialog -->
    <rom-dlg ref="ROM_DLG" @done="romDone"/>
    <batch-dlg ref="BATCH_DLG" @done="romDone"/>
  </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import RomDlg from '../dialog/RomDlg.vue'
import ConditionQuery from '../fun_mod/ConditionQuery.vue'
import PageDiv from '../fun_mod/PageDiv.vue'
import http from '@/axios/http'
import util from '@/assets/js/util'
import BatchDlg from '../dialog/BatchDlg.vue'
import { ElNotification } from 'element-plus'
import mqtt from '@/assets/js/mqtt'
export default {
  components: { 
    RomDlg,
    ConditionQuery,
    PageDiv,
    BatchDlg
  },
  props:['data'],
  setup() {
    const Global = getCurrentInstance().proxy
    let user = reactive({
      id: Global.$var.user.id,
      username: Global.$var.user.username,
      power: Global.$var.user.power,
    });

    onMounted(()=>{
      sessionStorage.removeItem('rBatchData')
      mqttOnMsg()
      getRoms()
    })

    function mqttOnMsg() {
      mqtt.onMsg((t,m)=>{
        loading.value = false
        let r = JSON.parse(m)
        // console.log(r)
        if (r.data.returnCode == 10000) {
          let d = r.data.data
          if (r.msgType == 155) {
          //console.log(d)
            for (let i in d) {
              let lastEditonInfos = d[i].edition_infos[d[i].edition_infos.length - 1]
              d[i].lastVerion = lastEditonInfos.version || '尚未设置固件版本'
              d[i].lastEdtion = lastEditonInfos.edition || ''
            }
            romList.value = d
            paging.total = r.data.count
            if (PAGING_COM.value) PAGING_COM.value.setData(paging)
          }
        }  
      })
    }

    let romList = ref([])
    let loading = ref(false)
    function getRoms() {
      loading.value = true
      let msgCode = 155
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.firmware_name = searchKey.firmware_name
      m.factory = searchKey.factory
      m.model = searchKey.model
      m.edition = searchKey.edition
      m.version = searchKey.version
      m.indexPage = paging.index
      m.pageSize = paging.size
      g.message = m
    //console.log('固件查询:',JSON.stringify(g))
      mqtt.publish(topic,JSON.stringify(g))
    }
    // 多选
    let batchData = []
    function handleSelectionChange(e) {
      batchData = e
      sessionStorage.setItem('rBatchData',JSON.stringify(e))
    }

    // 分页
    let PAGING_COM = ref(null)
    let paging = reactive({
      total: 0,
      index: 1,
      size: 100
    })
    function pageChange(e) {
      paging.index = e
      getRoms()
    }
    // 搜索
    let searchKey = reactive({
      words: '',
      firmware_name: '',
      factory: '',
      model: '',
      edition: '',
      version: '',
    })
    function searchDone(e) {
      searchKey.words = ''
      searchKey.firmware_name = ''
      searchKey.factory = ''
      searchKey.model = ''
      searchKey.edition = ''
      searchKey.version = ''
      e.forEach(v=>{
        if (v.t == '固件名称') searchKey.firmware_name = v.v
        if (v.t == '主板厂商') searchKey.factory = v.v
        if (v.t == '主板型号') searchKey.model = v.v
        if (v.t == '固件版本名称') searchKey.edition = v.v
        if (v.t == '固件版本号') searchKey.version = v.v
      })
      paging.index = 1
      getRoms()
    }

    // 编辑固件
    let ROM_DLG = ref(null)
    let romInfo = ref({name: ''})
    function handleBtn(index,row,f) {
      let bd = JSON.parse(sessionStorage.getItem('rBatchData')) || []
      let l = bd.length
      // if (l > 0) {
      //   ElNotification({
      //     type: 'warning',
      //     title: '当前已选中'+l+'条记录',
      //     message: '选中多条数据请使用批量处理'
      //   })
      //   return
      // }
      row.flag = f
      // romInfo.value = row
      ROM_DLG.value.open(row)
    }
    // 批量处理固件
    let BATCH_DLG = ref(null)
    function handleBatch() {
      let bd = JSON.parse(sessionStorage.getItem('rBatchData'))  || []
      if (batchData.length < bd.length) batchData = bd
      let e = {}
      e.flag = 'rom'
      e.data = batchData
      BATCH_DLG.value.open(e)
    } 
    // 固件编辑完成
    function romDone(e) {      
      setTimeout(()=>{
        getRoms()
      },1)  
    }

    function isNull(v) {
      return util.isNull(v)
    }

    return{
      user, romList, loading, handleSelectionChange, PAGING_COM, paging, pageChange, searchKey, searchDone,
      ROM_DLG,romInfo, handleBtn, BATCH_DLG, handleBatch, romDone, 
      isNull
    }
  },
}
</script>

<style lang="scss" scoped src="./tab_content2.scss"></style>